<template>
  <el-container class="user-data">
    <el-container>
      <el-form :inline="true" :model="searchParamForm" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="searchParamForm.username" clearable/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchParamForm.email" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="clearSearchParam">清空条件</el-button>
          <el-button type="primary" @click="onSearchSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="addDrawerOpen">新增用户</el-button>
    </el-container>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="id" label="#" width="180"/>
      <el-table-column prop="loginName" label="用户名" width="180"/>
      <el-table-column prop="headerImg" label="用户头像">
        <template #default="scope">
          <el-avatar :src="scope.row.headerImg" size="small" shape="square"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="accountStatus" label="激活状态">
        <template #default="scope">
          <!--  scope 代表这一行数据-->
          <el-switch
              v-model="scope.row.accountStatus"
              :active-value="1"
              :inactive-value="0"
              class="ml-2"
              inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              active-text="已激活"
              inactive-text="未激活"
              @change="updateAccountStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="safeEmail" label="安全邮箱"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" size="small" @click="updateUser(scope.row)"/>
          <el-button type="danger" :icon="Delete" size="small" @click="deleteUser(scope.row.id)"/>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background
                   layout="prev, pager, next" :total="totalRecords"
                   @current-change="currentPage"
                   :current-page="pnRef"
    />
  </el-container>


  <!--  用户数据录入抽屉  -->
  <el-drawer v-model="drawer" :title="drawerTitle" :with-header="true">
    <el-form
        label-position="right"
        label-width="100px"
        :model="addUserData"
        style="max-width: 460px"
    >
      <el-form-item label="用户id" style="display: none">
        <el-input v-model="addUserData.id"/>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input :disabled="loginUserDisable" v-model="addUserData.loginName"/>
      </el-form-item>
      <el-form-item label="登录密码">
        <el-input v-model="addUserData.loginPwd"/>
      </el-form-item>
      <el-form-item label="安全邮箱">
        <el-input v-model="addUserData.safeEmail"/>
      </el-form-item>
      <el-form-item label="首次激活">
        <el-switch
            v-model="addUserData.accountStatus"
            inline-prompt
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 150px" @click="addUserSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import {onMounted, ref, reactive} from "vue";
import {getUserPageData, addUserDataAPI, deleteUserAPI,updateUserAPI} from "@/api/sys/userapi"
import {ElMessage} from 'element-plus'
import {
  Delete,
  Edit
} from '@element-plus/icons-vue'
//==============新增用户-抽屉==============
const drawer = ref(false);
const drawerTitle = ref("");
const addUserData = ref({});
const loginUserDisable = ref(false);
//自己加一堆判断

const addUserSubmit = () => {
  let result = null;
  if (addUserData.value.id != null) {
    //有id。是修改
    updateUserAPI(addUserData.value).then(resp => {
      if (resp.data.code === 200) {
        ElMessage.success("用户修改成功");
        drawer.value = false;
        renderUserTable(pnRef.value);
        addUserData.value = {} //数据清空
      } else {
        ElMessage.error(resp.data.message);
      }
    });
  }else {
    //无id，是新增
    addUserDataAPI(addUserData.value).then(resp => {
      if (resp.data.code === 200) {
        ElMessage.success("用户新增成功");
        drawer.value = false;
        //发送请求问后端，现在总共多少页； 计算下要去那一页
        let pnHaha = Math.ceil((totalRecords.value+1)/10);
        console.log("准备去：",pnHaha)
        searchParamForm.value = {};
        renderUserTable(pnHaha);
        addUserData.value = {}
      } else {
        ElMessage.error(resp.data.message);
      }
    });
  }


}
//===============CRUD  -- API=====================
const addDrawerOpen = () => {
  addUserData.value = {}
  drawerTitle.value = "新增用户";
  drawer.value = true;
  loginUserDisable.value=false;
}
const updateAccountStatus = (row) => {
  console.log("需要修改的数据：", row)
}

const updateUser = (row) => {
  //1、打开抽屉
  drawer.value = true;
  drawerTitle.value = "修改用户";
  loginUserDisable.value=true;
  //2、回显数据
  console.log("数据：", row.id)
  console.log("数据：", row.loginName)
  addUserData.value = {
    id: row.id,
    loginName: row.loginName,
    loginPwd: "",
    safeEmail: row.safeEmail,
    accountStatus: row.accountStatus
  }

}
const deleteUser = (id) => {
  deleteUserAPI(id)
      .then(resp => {
        if (resp.data.code === 200) {
          ElMessage.success("删除成功");
          renderUserTable(pnRef.value)
        }
      })
}

//==============搜索表单==============

const  clearSearchParam = ()=>{
  searchParamForm.value = {};
  renderUserTable(1);
}

// reactive：包装不了基本类型的响应式 直接 xxx.属性 就能响应式修改值
// ref：     全类型都能用。 需要使用 xxx.value.属性 才能响应修改值
// 标准：对象：优先用 reactive；  普通：优先用 ref；   不确定：ref
const searchParamForm = ref({
  username: '',
  email: ''
})

const onSearchSubmit = () => {
  //发请求
  console.log('准备搜索!',searchParamForm.value)
  renderUserTable(pnRef.value)
}
//============================================

//==============表格分页========================
const tableData = ref([])
const totalRecords = ref(1000);
const pnRef = ref(1);//记录当前页码
const totalPages = ref(1);//记录总页码
const currentPage = (pn) => {
  pnRef.value = pn;
  renderUserTable(pnRef.value);
}
//页面加载获取用户数据
onMounted(() => {
  pnRef.value = 1;
  renderUserTable(pnRef.value);
})
//=======================================

//渲染用户表格数据
const renderUserTable = (pn) => {
  pnRef.value = pn;
  //传入页码，传入搜索条件
  getUserPageData(pnRef.value,searchParamForm.value)
      .then(resp => {
        // 后端返回的是 resp.data = {code:xx,msg:xx,data:}
        tableData.value = resp.data.data.records;
        totalRecords.value = resp.data.data.total;
        pnRef.value = resp.data.data.current;
      })
}


</script>

<style scoped>
.user-data {
  flex-direction: column;
}

.el-pagination {
  margin-top: 20px;
}
</style>
